package intel;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @description: 客户端向服务器端发送文件，服务器收到后保存起来
 * @author: apple
 * @date:  2021/12/26 12:57 下午
 * @version 1.0
 **/
public class TCPTest2 {
    // 服务器端的端口
    static final int port = 8899;
    @Test
    public void client() throws IOException {
        // 服务器端的IP
        final InetAddress byName = InetAddress.getByName("127.0.0.1");
        Socket socket = new Socket(byName, port);
        System.out.println("链接服务成功...");
        OutputStream outputStream = socket.getOutputStream();
        // 读取一个文件进来
        BufferedInputStream in = new BufferedInputStream(new FileInputStream("1.webp"));
        byte[] buffers = new byte[1024];
        int len;
        while ((len =  in.read(buffers)) != -1) {
            outputStream.write(buffers,0,len);
        }
        System.out.println("发送图片成功....");
        in.close();
        socket.shutdownOutput(); // 告诉服务器图片传输完成
//        // 接收服务器端发送的消息
        InputStream inputStream = socket.getInputStream();
        System.out.println(inputStream.getClass());
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffers2 = new byte[1024];
        int len2;
        while ((len2 =  inputStream.read(buffers2)) != -1) {
            byteArrayOutputStream.write(buffers2,0,len2);
        }
        String serverMsg = byteArrayOutputStream.toString();
        System.out.println("来自服务器的消息：" + serverMsg);
        byteArrayOutputStream.close();
        inputStream.close();
        outputStream.close();
        socket.close();
        System.out.println("客户端关闭成功！");
    }

    @Test
    public void server() throws IOException {
        ServerSocket serverSocket = new ServerSocket(port);
        // 服务挂起，等待客户端发起请求，获取Socket对象（包含客户端各种信息）
        System.out.println("服务器挂起..........");
        Socket accept = serverSocket.accept();
        System.out.println("服务器收到了客户端请求.......");
        InputStream in = accept.getInputStream();
        FileOutputStream outputStream = new FileOutputStream("2.webp");
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
        byte[] buffers = new byte[1024];
        int len;
        while ((len =  in.read(buffers)) != -1) {
            bufferedOutputStream.write(buffers,0,len);
        }
        System.out.println("图片保存成功！");
        bufferedOutputStream.flush();
        bufferedOutputStream.close();

        System.out.println("准备给客户端发送消息");
        // 服务器端反馈给客户端
        OutputStream out = accept.getOutputStream();
        out.write("收到你发的图片了".getBytes());
        out.close();

        in.close();
        accept.close();
        serverSocket.close();
        System.out.println("服务器关闭成功");
    }

}
